<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree v-bind:tree-data="treeData"
                v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData"
                       @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>小区名称：<el-input placeholder="请输入小区名称"
                        v-model="queryData.name"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>物业公司：<el-input placeholder="请输入物业公司"
                        v-model="queryData.propertyCompany"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>负责人：<el-input placeholder="请输入物业负责人"
                        v-model="queryData.propertyPrincipal"
                        clearable
                        class="dzy-custom-input"></el-input>
            </div>
            <div>
              <el-button @click="searchHandleClick"
                         type="primary"
                         icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table :page-data="pageData"
                     :table-columns="tableColumns"
                     v-on:currentChange="handleCurrentChange"
                     v-on:handleCheckedRows="handleCheckedRows"
                     v-on:checkSingleRow="checkSingleRow"
                     v-on:changeSingleRow="changeSingleRow"
                     v-on:deleSingleRow="deleSingleRow" />
          <el-dialog :title="dialogTitle"
                     :visible.sync="dialogFormVisible"
                     :before-close="close">
            <el-form :model="formData"
                     :rules="rules"
                     ref="formData"
                     :disabled="showOnly"
                     label-width="140px"
                     size="mini">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="网格"
                                prop="allGridIdArr">
                    <!-- <grid-cascader v-model="formData.allGridId"></grid-cascader> -->
                    <div class="block">
                          <el-cascader placeholder="请选择"
                            :options="treeOption"
                            filterable
                            clearable
                            :props="gridIdProps"
                            v-model="formData.allGridIdArr">
                          </el-cascader>
                        </div>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="小区名称"
                                prop="name">
                    <el-input v-model="formData.name"
                              placeholder="请输入小区名称"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="楼栋数"
                                prop="buildingNum">
                    <el-input v-model="formData.buildingNum"
                              placeholder="请输入楼栋数"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总户数">
                    <el-input v-model="formData.familyNum"
                              placeholder="请输入总户数"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="总面积(㎡)"
                                prop="allArea">
                    <el-input v-model="formData.allArea"
                              placeholder="请输入总面积(㎡)"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="住宅面积(㎡)"
                                prop="houseArea">
                    <el-input v-model="formData.houseArea"
                              placeholder="请输入住宅面积(㎡)"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="商业面积(㎡)"
                                prop="businessArea">
                    <el-input v-model="formData.businessArea"
                              placeholder="请输入商业面积(㎡)"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="是否有物业"
                                prop="hasProperty">
                    <el-select filterable
                                   v-model="formData.hasProperty"
                                   placeholder="是否有物业">
                          <el-option :key="0"
                                     :value="0"
                                     label="无物业"></el-option>
                          <el-option :key="1"
                                     :value="1"
                                     label="有物业"></el-option>
                        </el-select>
                  </el-form-item>
                </el-col>
                <template v-if='formData.hasProperty'>
                  <el-col :span="12">
                    <el-form-item label="物业用房面积(㎡)"
                                  prop="propertyArea">
                      <el-input v-model="formData.propertyArea"
                                placeholder="请输入物业用房面积(㎡)"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物业公司"
                                  prop="propertyCompany">
                      <el-input v-model="formData.propertyCompany"
                                placeholder="请输入物业公司"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="物业负责人"
                                  prop="propertyPrincipal">
                      <el-input v-model="formData.propertyPrincipal"
                                placeholder="请输入物业负责人"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话"
                                  prop="propertyPhone">
                      <el-input v-model="formData.propertyPhone"
                                placeholder="请输入联系电话"></el-input>
                    </el-form-item>
                  </el-col>
                </template>
                <el-col :span="24">
                  <el-form-item label="备注"
                                    style="width:100%"
                                    prop="remark">
                        <el-input v-model="formData.introduction"
                                  type="textarea"
                                  :rows="3"
                                  placeholder="请输入备注"></el-input>
                      </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="照片">
                    <app-upload ref="appUpload"
                                v-model="formData.communityPic"></app-upload>
                  </el-form-item>
                </el-col>
              </el-row>

            </el-form>
            <div v-if="!showOnly"
                 slot="footer"
                 class="dialog-footer">
              <el-button @click="cancel('formData')">取 消</el-button>
              <el-button type="primary"
                         :disabled="showOnly"
                         @click="save('formData')">提 交</el-button>
            </div>
          </el-dialog>
          <!-- <el-dialog class="dialog-body-mini"
                     :visible.sync="showMap"
                     title="绘制地图"
                     width="70%"
                     top="8vh"
                     :before-close="mapCancel">
            <edit-map v-if="mapHackReset"
                      mode="full"
                      @appMapCallback="appMapCallback"
                      :row-id="currentSelectedRowId"
                      :target="mapTarget"></edit-map>
          </el-dialog> -->
          <el-dialog :visible.sync="showMap" title="绘制地图" width="70%" top="8vh" :before-close="mapCancel">
              <edit-map v-if="mapHackReset" mode="full" @appMapCallback="appMapCallback" :row-id="currentSelectedRowId" :target="mapTarget" ></edit-map>
            </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppTree from '@/components/common/AppTree'
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import EditMap from '@/components/EditMap'
import AppUpload from '@/components/AppUpload'
import { getCaseAllGridIdByGridTreeData, isCommonDo } from '@/utils/CommonUtil'
import { findCommunity, updateCommunity, deleteCommunity, createCommunity, getCommunity } from '@/http/FangWuGuanLiApi'
import { createMapLocation, updateMapLocation } from '@/http/AppApi'
import { getUserGridTree } from '@/utils/SessionDataUtil'
// import { validatePhone } from '@/utils/validate'
import { getAllRegion } from '@/utils/region'
export default {
  data () {
    return {
      tableData: [],
      pageData: {},
      formData: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      treeOption: [],
      queryData: {},
      treeData: [],
      dialogTitle: '',
      dialogFormVisible: false,
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      mapTarget: {},
      mapPathList: [],
      mapHackReset: false,
      tableColumns: [
        { label: '小区名', prop: 'name' },
        { label: '物业公司', prop: 'propertyCompany' },
        { label: '物业负责人', prop: 'propertyPrincipal' },
        { label: '联系电话', prop: 'propertyPhone' },
        { label: '地图标注', prop: 'mapMarkStatus' }
      ],
      rules: {
        allGridIdArr: [{
          required: true,
          message: '选择网格',
          trigger: 'blur'
        }],
        name: [{
          required: true,
          message: '请输入小区名称',
          trigger: 'blur'
        }],
        buildingNum: [{
          required: true,
          message: '请输入楼栋数',
          trigger: 'blur'
        }],
        // familyNum: [{
        //   required: true,
        //   message: '请输入总户数',
        //   trigger: 'blur'
        // }],
        houseArea: [{
          required: true,
          message: '请输入住宅面积(㎡)',
          trigger: 'blur'
        }],
        businessArea: [{
          required: true,
          message: '请输入商业面积(㎡)',
          trigger: 'blur'
        }],
        propertyArea: [{
          required: false,
          message: '请输入物业用房面积(㎡)',
          trigger: 'blur'
        }],
        allArea: [{
          required: true,
          message: '请输入总面积(㎡)',
          trigger: 'blur'
        }],
        propertyCompany: [{
          required: false,
          message: '请输入物业公司',
          trigger: 'blur'
        }],
        propertyPrincipal: [{
          required: false,
          message: '请输入物业负责人',
          trigger: 'blur'
        }],
        propertyPhone: [{
          required: false,
          message: '请输入联系电话',
          trigger: 'blur'
        }],
        introduction: [{
          required: false,
          message: '请输入简介',
          trigger: 'blur'
        }]
      }
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    EditMap,
    AppUpload
  },
  mounted () {
    this.getTableData()
    this.getTreeData()
  },
  methods: {
    save (formName) {
      console.log(this.formData)
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false
          if (this.formData) {
            this.beforeSubmit()
            if (this.formData.id) {
              updateCommunity(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancel(formName)
                  this.$message({
                    type: 'success',
                    message: '修改成功'
                  })
                }
              })
            } else {
              createCommunity(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancel(formName)
                  this.dialogFormVisible = false
                  this.$refs[formName].resetFields()
                  this.$message({
                    type: 'success',
                    message: '添加成功'
                  })
                }
              })
            }
          }
        }
      })
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            deleteCommunity(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel (formName) {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.showMap = false
      this.mapHackReset = false
      this.$refs[formName].resetFields()
    },
    close () {
      this.mapCancel()
      this.dialogFormVisible = false
      this.formData = {}
      this.showMap = false
      this.mapHackReset = false
      this.$refs['formData'].resetFields()
    },
    beforeSubmit () {
      if (this.formData.allGridIdArr && this.formData.allGridIdArr.length !== 0) {
        let liveIndex = this.formData.allGridIdArr.length - 1
        let liveData = {}
        liveData.id = this.formData.allGridIdArr[liveIndex]
        liveData.items = this.treeData
        liveData.isGetAllId = true
        this.formData.allGridId = getAllRegion(liveData)
      } else {
        this.formData.allGridId = ''
      }
      return true
    },
    getTableData () {
      let param = this.queryData
      findCommunity(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        }
      })
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getTreeData () {
      let gridTree = getUserGridTree()
      if (gridTree && gridTree instanceof Array) {
        this.treeData = gridTree
        this.treeOption = gridTree
      }
    },
    treeClickHandle (data) {
      this.queryData = {}
      this.queryData.likeAllGridId = data.id
      this.getTableData()
      this.formData.allGridId = getCaseAllGridIdByGridTreeData(data)
      this.formData.allGridIdArr = this.formData.allGridId.split(',')
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else if (callbackData.btnType === 'draw') {
        let rowData = callbackData.rows[0]
        if (!rowData) {
          alert('请选择数据')
          return
        }
        this.mapHackReset = true
        this.showMap = true
        let target = {}
        target.targetId = rowData.id
        target.targetType = 'community'
        this.mapTarget = target
      } else {
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
        if (callbackData.btnType === 'post') {
          this.formData = this.formData.allGridId ? this.formData : {}
        } else {
          this.formData = JSON.parse(JSON.stringify(callbackData.rows[0]))
          let id = this.formData.id
          getCommunity(id).then(resp => {
            if (resp.code && resp.code === '200') {
              let data = resp.data
              this.formData = data
              let regionData = {}
              regionData.id = this.formData.gridId
              regionData.items = this.treeData
              let gridIdArr = getAllRegion(regionData)
              this.$set(this.formData, 'allGridIdArr', gridIdArr)
            }
          })
        }
      }
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
        this.currentSelectedRowId = rows[0].id
      } else {
        this.currentSelectedData = []
      }
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.target) {
        let mapLocation = {}
        if (appMapInfo.poly && appMapInfo.poly instanceof Array && appMapInfo.poly.length > 0) {
          let length = appMapInfo.poly.length
          this.saveMapLocationInfoByArray(0, length, appMapInfo)
        } else {
          mapLocation = this.appMapInfo2MapLocation(appMapInfo)
          this.saveMapLocationInfo(mapLocation)
        }
      }
      return ''
    },
    appMapInfo2MapLocation (appMapInfo) {
      let mapLocation = {}
      mapLocation.targetId = appMapInfo.target.targetId
      mapLocation.targetType = appMapInfo.target.targetType

      if (!appMapInfo.poly) {
        mapLocation.mapArea = appMapInfo.polyPathArr
        mapLocation.mapColor = appMapInfo.polyColor
        // 地图信息id存在则不允许修改targetId和targetType
        if (appMapInfo.id) {
          mapLocation.id = appMapInfo.id
          delete mapLocation.targetId
          delete mapLocation.targetType
        }
      }
      if (appMapInfo.clearStatus) {
        mapLocation.clearStatus = appMapInfo.clearStatus
      }
      if (appMapInfo.markPosition) {
        mapLocation.longitude = appMapInfo.markPosition.lng
        mapLocation.latitude = appMapInfo.markPosition.lat
      }
      return mapLocation
    },
    saveMapLocationInfoByArray (i, length, appMapInfo) {
      if (i >= length) {
        return
      }
      let mapLocation = {}
      mapLocation = this.appMapInfo2MapLocation(appMapInfo)
      mapLocation.mapArea = appMapInfo.poly[i].polyPathArr
      mapLocation.mapColor = appMapInfo.poly[i].polyColor
      mapLocation.id = appMapInfo.poly[i].id
      if (mapLocation.id) {
        delete mapLocation.targetId
        delete mapLocation.targetType
      }
      i++
      let data = mapLocation
      console.log('maplocation id = ' + mapLocation.id)
      if (mapLocation.id) {
        updateMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(data).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
            this.saveMapLocationInfoByArray(i, length, appMapInfo)
          } else {
            console.log(resp.message)
          }
        })
      }
    },
    saveMapLocationInfo (mapLocation) {
      if (mapLocation.id) {
        updateMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('修改成功')
          } else {
            console.log(resp.message)
          }
        })
      } else {
        createMapLocation(mapLocation).then(resp => {
          if (resp.code && resp.code === '200') {
            console.log('保存成功')
          }
        })
      }
      this.mapCancel()
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    }
  },
  computed: {},
  watch: {}
}
</script>
<style scoped>
.el-form >>> .el-input__inner {
  height: 37px;
}
.el-form >>> .el-form-item__label {
  line-height: 37px;
}
.el-form >>> .el-cascader__label {
  line-height: 37px;
}
</style>
